package ink.metoo.gude.util

object GravatarUtils {


    private const val BASE_URL = "https://cravatar.com/avatar/"
    private const val DEFAULT_SIZE = 80
    private const val MAX_SIZE = 2048
    private const val MIN_SIZE = 1

    /**
     * 生成Gravatar头像URL
     *
     * @return Gravatar头像URL
     */
    @JvmStatic
    fun generateUrl(
        key: String,
        size: Int = DEFAULT_SIZE,
    ): String {
        val hash = MessageDigestUtils.md5(key)
        val url = StringBuilder(BASE_URL).append(hash)

        val params = mutableListOf<String>()

        // 处理尺寸参数
        val validSize = size.coerceIn(MIN_SIZE, MAX_SIZE)
        if (validSize != DEFAULT_SIZE) {
            params.add("s=$validSize")
        }

        if (params.isNotEmpty()) {
            url.append("?").append(params.joinToString("&"))
        }

        return url.toString()
    }

}